import Foundation

// MARK: - 优惠券分页响应
struct CouponResponse: Codable {
    let list: [Coupon]
    let count: Int?
    let page: Int
    let limit: Int
    let totalPage: Int?
    let total: Int?
}

// MARK: - 优惠券详情
struct Coupon: Codable, Identifiable {
    let id: Int
    let uid: Int?
    let merId: Int?
    let name: String
    let publisher: Int?
    let category: Int?
    let couponType: Int?
    let money: Double
    let discount: Double?
    let minPrice: Double
    let isLimited: Bool?
    let total: Int?
    let lastTotal: Int?
    let receiveStartTime: String?
    let receiveEndTime: String?
    let startTime: String?
    let endTime: String?
    let isFixedTime: Bool?
    let day: Int?
    let isUse: Bool?
    let useStartTimeStr: String?
    let useEndTimeStr: String?
    let validStr: String? // usable, unusable, overdue, notStart
    let status: Bool?
    let isUserReceive: Bool?
    let productVoList: [CouponProduct]?
    
    // 为了兼容UI显示，添加计算属性
    var title: String {
        return name
    }
    
    var couponPrice: Double {
        return money
    }
    
    var useMinPrice: Double {
        return minPrice
    }
    
    var couponTime: Int {
        return day ?? 0
    }
}

// MARK: - 优惠券关联商品
struct CouponProduct: Codable, Identifiable {
    let id: Int
    let image: String
    let name: String?
    let price: Double
    let stock: Int?
    
    enum CodingKeys: String, CodingKey {
        case id
        case image
        case name
        case price
        case stock
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        image = try container.decode(String.self, forKey: .image)
        name = try container.decodeIfPresent(String.self, forKey: .name)
        
        // price 可能是字符串或数字，需要特殊处理
        if let priceString = try? container.decode(String.self, forKey: .price) {
            price = Double(priceString) ?? 0.0
        } else {
            price = try container.decode(Double.self, forKey: .price)
        }
        
        stock = try container.decodeIfPresent(Int.self, forKey: .stock)
    }
}

// MARK: - 用户优惠券响应
struct UserCouponResponse: Codable {
    let page: Int
    let limit: Int
    let totalPage: Int
    let total: Int
    let list: [Coupon]
}

// MARK: - 领券中心响应
struct CouponCollectionResponse: Codable {
    let page: Int
    let limit: Int
    let totalPage: Int
    let total: Int
    let list: [Coupon]
}